package com.huhao.wshare.Friends;

import static com.huhao.wshare.Config.FRIEND_REQUEST_API;
import static com.huhao.wshare.Config.GET_USER_PROFILE_API;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import com.bumptech.glide.Glide;
import com.huhao.wshare.BaseActivity;
import com.huhao.wshare.R;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.IOException;

public class AddFriendProfileActivity extends BaseActivity {

    private TextView tvUsername, tvAccount, tvEmail, tvPhone, tvSigns;
    private ImageView ivAvatar, ivBackground, ivGender;
    private Button btnAddFriend;
    private String token;
    private OkHttpClient client = new OkHttpClient();
    private boolean isFriend;
    private long userId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_friend_profile);

        // 初始化视图
        tvUsername = findViewById(R.id.tvUsername);
        tvAccount = findViewById(R.id.tvAccount);
        tvEmail = findViewById(R.id.tvEmail);
        tvPhone = findViewById(R.id.tvPhone);
        tvSigns = findViewById(R.id.tvSigns);
        ivAvatar = findViewById(R.id.ivAvatar);
        ivBackground = findViewById(R.id.background_image);
        ivGender = findViewById(R.id.ivGender);
        btnAddFriend = findViewById(R.id.btnAddFriend);

        // 从 SharedPreferences 中获取 token
        SharedPreferences sp = getSharedPreferences("user_prefs", MODE_PRIVATE);
        token = sp.getString("token", null);

        // 获取传递过来的 userId
        userId = getIntent().getLongExtra("userId", -1);
        isFriend = getIntent().getBooleanExtra("isFriend", false);

        // 根据是否为好友决定是否显示添加好友按钮
        if (isFriend) {
            btnAddFriend.setVisibility(View.GONE);
        } else {
            btnAddFriend.setVisibility(View.VISIBLE);
            // 设置按钮点击监听器
            btnAddFriend.setOnClickListener(v -> showAddFriendDialog());
        }

        if (userId != -1 && token != null) {
            fetchFriendProfile(userId);
        } else {
            Toast.makeText(this, "用户已失效", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void fetchFriendProfile(long userId) {
        String url = GET_USER_PROFILE_API + "/" + userId;
        Request request = new Request.Builder()
                .url(url)
                .get()
                .addHeader("Authorization", "Bearer " + token)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                runOnUiThread(() -> Toast.makeText(AddFriendProfileActivity.this, "网络错误，请稍后重试", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String respStr = response.body() != null ? response.body().string() : "";
                    runOnUiThread(() -> handleFriendProfileResponse(respStr));
                } else {
                    Log.d("Response code", String.valueOf(response.code()));
                    runOnUiThread(() -> Toast.makeText(AddFriendProfileActivity.this, "获取用户信息失败，请稍后重试", Toast.LENGTH_SHORT).show());
                }
            }
        });
    }

    private void handleFriendProfileResponse(String respStr) {
        try {
            JSONObject json = new JSONObject(respStr);
            int code = json.optInt("code");
            if (code == 200) {
                JSONObject data = json.optJSONObject("data");
                if (data != null) {
                    // 更新 UI 组件的文本
                    tvUsername.setText(data.optString("username"));
                    tvAccount.setText("wshare账号：" + data.optString("account"));
                    tvEmail.setText(data.optString("email"));
                    tvPhone.setText(data.optString("phone"));
                    tvSigns.setText(data.optString("signs", "暂无个性签名"));

                    String avatarUrl = data.optString("avatar");
                    if (!data.isNull("avatar") && !avatarUrl.isEmpty()) {
                        Glide.with(this)
                                .load(avatarUrl)
                                .into(ivAvatar);
                    } else {
                        String gender = data.optString("gender");
                        if ("男".equals(gender)) {
                            ivAvatar.setImageResource(R.drawable.default_avatar_man);
                        } else if ("女".equals(gender)) {
                            ivAvatar.setImageResource(R.drawable.default_avatar_woman);
                        } else {
                            ivAvatar.setImageResource(R.drawable.default_avatar_man);
                        }
                    }

                    String bkImgUrl = data.optString("bkImg");
                    if (!data.isNull("bkImg") && !bkImgUrl.isEmpty()) {
                        Glide.with(this)
                                .load(bkImgUrl)
                                .into(ivBackground);
                    } else {
                        ivBackground.setImageResource(R.drawable.default_background);
                    }

                    String gender = data.optString("gender");
                    if ("男".equals(gender)) {
                        ivGender.setImageResource(R.drawable.ic_male);
                        ivGender.setVisibility(android.view.View.VISIBLE);
                    } else if ("女".equals(gender)) {
                        ivGender.setImageResource(R.drawable.ic_female);
                        ivGender.setVisibility(android.view.View.VISIBLE);
                    } else {
                        ivGender.setVisibility(android.view.View.GONE);
                    }
                }
            } else {
                Toast.makeText(this, json.optString("message"), Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "解析用户信息失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void showAddFriendDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("添加好友");

        // 加载输入框
        final EditText input = new EditText(this);
        input.setHint("为其添加备注...(选填)");
        builder.setView(input);

        // 设置确认按钮
        builder.setPositiveButton("确认", (dialog, which) -> {
            String remark = input.getText().toString().trim();
            if (TextUtils.isEmpty(remark)) {
                remark = "";
            }
            sendFriendRequest(remark);
        });

        // 设置取消按钮
        builder.setNegativeButton("取消", (dialog, which) -> dialog.cancel());

        builder.show();
    }

    private void sendFriendRequest(String remark) {
        try {
            // 构建请求体
            JSONObject requestBodyJson = new JSONObject();
            requestBodyJson.put("friendId", userId);
            requestBodyJson.put("remark", remark);

            // 定义请求体的媒体类型
            MediaType JSON = MediaType.get("application/json; charset=utf-8");
            RequestBody requestBody = RequestBody.create(requestBodyJson.toString(), JSON);

            // 构建请求
            String url = FRIEND_REQUEST_API;
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + token)
                    .build();

            // 发送请求
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    runOnUiThread(() -> Toast.makeText(AddFriendProfileActivity.this, "网络错误，请稍后重试", Toast.LENGTH_SHORT).show());
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String respStr = response.body() != null ? response.body().string() : "";
                        runOnUiThread(() -> handleFriendRequestResponse(respStr));
                    } else {
                        Log.d("Response code", String.valueOf(response.code()));
                        String errorBody = response.body() != null ? response.body().string() : "";
                        String errorMessage = "发送好友请求失败，请稍后重试";

                        try {
                            JSONObject errorJson = new JSONObject(errorBody);
                            errorMessage = errorJson.optString("message", errorMessage);
                        } catch (JSONException e) {
                            Log.e("FriendRequestError", "解析错误响应失败", e);
                        }
                        String finalErrorMessage = errorMessage;
                        runOnUiThread(() -> Toast.makeText(AddFriendProfileActivity.this, finalErrorMessage, Toast.LENGTH_SHORT).show());
                    }
                }
            });
        } catch (JSONException e) {
            runOnUiThread(() -> Toast.makeText(AddFriendProfileActivity.this, "构建请求体失败", Toast.LENGTH_SHORT).show());
        }
    }

    private void handleFriendRequestResponse(String respStr) {
        try {
            JSONObject json = new JSONObject(respStr);
            int code = json.optInt("code");
            if (code == 200) {
                Toast.makeText(this, "好友请求发送成功", Toast.LENGTH_SHORT).show();
                // 发送成功后隐藏按钮
                btnAddFriend.setVisibility(View.GONE);
            } else {
                String message = json.optString("message");
                Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            Toast.makeText(this, "解析响应信息失败", Toast.LENGTH_SHORT).show();
        }
    }
}